package zh.keep.all

import android.annotation.SuppressLint
import android.app.*
import android.content.Intent
import android.os.Build
import android.view.WindowManager
import android.widget.RemoteViews
import androidx.core.app.NotificationCompat
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.work.PeriodicWorkRequest
import androidx.work.WorkManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import zh.keep.all.work.TimingWorker
import java.util.concurrent.TimeUnit
import kotlin.coroutines.cancellation.CancellationException


class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        myContext = this
        ProcessLifecycleOwner.get().lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onStop(owner: LifecycleOwner) {
                super.onStop(owner)
                //处于后台
//                Utils.startService()
//                createNotificationForNormal()
                createDialog()
            }
        })
        //JobScheduler(无效)
//        PeriodicJobService.startScheduler(this)
        val uploadWorkRequest = PeriodicWorkRequest.Builder(
            TimingWorker::class.java,
            15,
            TimeUnit.MINUTES,
        ).build()
        WorkManager.getInstance(applicationContext).enqueue(uploadWorkRequest)
    }

    fun createDialog() {
        val builder = AlertDialog.Builder(this)
        builder.setTitle("外部弹窗")
        builder.setMessage("这是测试外部弹窗内容")
        builder.setPositiveButton("打开app") { dialog, which ->
            //拉起app
            val intent = Intent(this, MainActivity::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            this.startActivity(intent)
        }
        val dialog = builder.create()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //系统级dialog
            dialog.window?.setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY)
        }
        try {
            dialog.show()
        } catch (e: Throwable) {
            e.printStackTrace()
        }
    }

    @SuppressLint("RemoteViewLayout")
    private fun createNotificationForNormal() {
        val channelId = "1"
        val mManager: NotificationManager =
            this.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        // 适配8.0及以上 创建渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                channelId,
                "test",
                NotificationManager.IMPORTANCE_HIGH
            ).apply {
                description = "描述"
                setShowBadge(true) // 是否在桌面显示角标
            }
            mManager.createNotificationChannel(channel)
        }
        // 添加自定义通知view
        val views = RemoteViews(packageName, R.layout.notifa_layout)
        // 点击意图
        val intent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
        // 构建配置
        val mBuilder = NotificationCompat.Builder(this, channelId)
            .setCustomBigContentView(views)
            .setFullScreenIntent(pendingIntent, true)
            .setSmallIcon(R.mipmap.ic_launcher) // 小图标
            .setStyle(NotificationCompat.BigTextStyle())
            .setPriority(NotificationCompat.PRIORITY_HIGH) // 设置优先级
            .setAutoCancel(false) // 是否自动消失（点击）
        // 发起通知
        mManager.notify(1, mBuilder.build())
    }

    companion object {
        lateinit var myContext: MyApplication
    }
}